<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="学期信息" prop="term">
        <el-input
          v-model="queryParams.term"
          placeholder="请输入学期信息，如 2024-2025学年 第二学期"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机房名称" prop="labName">
        <el-input
          v-model="queryParams.labName"
          placeholder="请输入机房名称，如 本校区-博学楼-博学楼机房1"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="节次" prop="classSection">
        <el-input
          v-model="queryParams.classSection"
          placeholder="请输入节次，如 早1、1 08:30-09:15"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="周一机房" prop="mondayUsage">
        <el-input
          v-model="queryParams.mondayUsage"
          placeholder="请输入周一机房使用信息，包括班级、课程、教师等"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="周二机房" prop="tuesdayUsage">
        <el-input
          v-model="queryParams.tuesdayUsage"
          placeholder="请输入周二机房使用信息，包括班级、课程、教师等"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="周三机房" prop="wednesdayUsage">
        <el-input
          v-model="queryParams.wednesdayUsage"
          placeholder="请输入周三机房使用信息，包括班级、课程、教师等"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="周四机房" prop="thursdayUsage">
        <el-input
          v-model="queryParams.thursdayUsage"
          placeholder="请输入周四机房使用信息，包括班级、课程、教师等"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="周五机房" prop="fridayUsage">
        <el-input
          v-model="queryParams.fridayUsage"
          placeholder="请输入周五机房使用信息，包括班级、课程、教师等"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['ao:lab-schedule:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>


        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ao:lab-schedule:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['ao:lab-schedule:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>

      <!-- 视图切换 -->
      <el-form-item>
        <el-radio-group v-model="viewMode" @change="handleViewModeChange">
          <el-radio-button value="table">表格视图</el-radio-button>
          <el-radio-button value="schedule">课程表视图</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap v-if="viewMode === 'table'">
    <div class="table-container">
      <el-table
          row-key="id"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange"
          style="width: 100%; margin: 0 auto; min-width: 1200px;"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column type="selection" width="55" />

        <!-- 基本信息列 -->
        <el-table-column label="基本信息" width="280" fixed="left">
          <template #default="scope">
            <div class="basic-info">
              <div class="info-row">
                <el-tag type="primary" size="small">{{ scope.row.term }}</el-tag>
              </div>
              <div class="info-row">
                <strong>{{ scope.row.labName }}</strong>
              </div>
              <div class="info-row">
                <el-tag size="small">{{ scope.row.classSection }}</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 课程表列 -->
        <el-table-column label="周一" align="center" min-width="200">
          <template #default="scope">
            <div class="course-cell" :title="scope.row.mondayUsage">
              {{ scope.row.mondayUsage || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="周二" align="center" min-width="200">
          <template #default="scope">
            <div class="course-cell" :title="scope.row.tuesdayUsage">
              {{ scope.row.tuesdayUsage || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="周三" align="center" min-width="200">
          <template #default="scope">
            <div class="course-cell" :title="scope.row.wednesdayUsage">
              {{ scope.row.wednesdayUsage || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="周四" align="center" min-width="200">
          <template #default="scope">
            <div class="course-cell" :title="scope.row.thursdayUsage">
              {{ scope.row.thursdayUsage || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="周五" align="center" min-width="200">
          <template #default="scope">
            <div class="course-cell" :title="scope.row.fridayUsage">
              {{ scope.row.fridayUsage || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['ao:lab-schedule:update']"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['ao:lab-schedule:delete']"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </ContentWrap>

  <!-- 课程表视图 -->
  <ContentWrap v-if="viewMode === 'schedule'">
    <div class="schedule-view">
      <!-- 按机房分组显示课程表 -->
      <div v-for="labGroup in groupedByLab" :key="labGroup.labName" class="class-schedule-card">
        <div class="class-header">
          <h3>{{ labGroup.labName }}</h3>
          <div class="class-info">
            <el-tag type="primary">{{ labGroup.term }}</el-tag>
          </div>
        </div>

        <!-- 课程表格 -->
        <el-table
          :data="labGroup.schedules"
          :stripe="true"
          :show-overflow-tooltip="true"
          class="schedule-table"
        >
          <el-table-column label="节次" width="140" align="center">
            <template #default="scope">
              <div class="section-cell">
                <div class="section-name">{{ scope.row.classSection }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="周一" min-width="180" align="center">
            <template #default="scope">
              <div class="schedule-course">{{ scope.row.mondayUsage || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="周二" min-width="180" align="center">
            <template #default="scope">
              <div class="schedule-course">{{ scope.row.tuesdayUsage || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="周三" min-width="180" align="center">
            <template #default="scope">
              <div class="schedule-course">{{ scope.row.wednesdayUsage || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="周四" min-width="180" align="center">
            <template #default="scope">
              <div class="schedule-course">{{ scope.row.thursdayUsage || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="周五" min-width="180" align="center">
            <template #default="scope">
              <div class="schedule-course">{{ scope.row.fridayUsage || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['ao:lab-schedule:update']"
                size="small"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['ao:lab-schedule:delete']"
                size="small"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 如果没有数据 -->
      <el-empty v-if="groupedByLab.length === 0" description="暂无课程表数据" />
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LabScheduleForm ref="formRef" @success="getList" />
  <!-- 导入弹窗 -->
  <LabScheduleImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { computed } from 'vue'
import download from '@/utils/download'
import { LabScheduleApi, LabSchedule } from '@/api/ao/labschedule'
import LabScheduleForm from './LabScheduleForm.vue'
import LabScheduleImportForm from './LabScheduleImportForm.vue'

/** 机房实训室课 列表 */
defineOptions({ name: 'LabSchedule' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<LabSchedule[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const viewMode = ref('table') // 视图模式：table 或 schedule
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  term: undefined,
  labName: undefined,
  classSection: undefined,
  mondayUsage: undefined,
  tuesdayUsage: undefined,
  wednesdayUsage: undefined,
  thursdayUsage: undefined,
  fridayUsage: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 按机房分组的计算属性
const groupedByLab = computed(() => {
  const groups = new Map()

  list.value.forEach(item => {
    const key = `${item.term}-${item.labName}`
    if (!groups.has(key)) {
      groups.set(key, {
        labName: item.labName,
        term: item.term,
        schedules: []
      })
    }
    groups.get(key).schedules.push(item)
  })

  // 对每个机房的课程按节次排序
  Array.from(groups.values()).forEach(group => {
    group.schedules.sort((a, b) => {
      return getSectionOrder(a.classSection) - getSectionOrder(b.classSection)
    })
  })

  return Array.from(groups.values())
})

/** 获取节次排序权重 */
const getSectionOrder = (classSection: string): number => {
  if (!classSection) return 999

  const section = classSection.toLowerCase().trim()

  // 定义节次排序规则
  const sectionOrder: { [key: string]: number } = {
    // 早读
    '早1': 1,
    '早读': 1,

    // 上午课程
    '1': 10,
    '第1节': 10,
    '第一节': 10,

    '2': 20,
    '第2节': 20,
    '第二节': 20,

    // 课间操
    '课间操': 25,
    '大课间': 25,
    '课间活动': 25,

    '3': 30,
    '第3节': 30,
    '第三节': 30,

    '4': 40,
    '第4节': 40,
    '第四节': 40,

    // 午休
    '午休': 45,
    '午间休息': 45,
    '中午休息': 45,

    // 下午课程
    '5': 50,
    '学习力': 50,
    '第五节': 50,

    '6': 60,
    '第6节': 60,
    '第六节': 60,

    '7': 70,
    '第7节': 70,
    '第七节': 70,

    '8': 80,
    '第8节': 80,
    '第八节': 80,

    // 晚自习
    '晚自习': 90,
    '晚1': 90,
    '晚2': 95,
    '晚3': 96
  }

  // 预处理：移除时间部分，只保留节次名称
  let sectionName = section
  // 匹配并移除时间格式 (如: "早1 07:40-08:20" -> "早1")
  const timePattern = /\s*\d{1,2}:\d{2}[-–]\d{1,2}:\d{2}/
  sectionName = sectionName.replace(timePattern, '').trim()

  // 首先尝试精确匹配
  for (const [key, order] of Object.entries(sectionOrder)) {
    if (sectionName === key.toLowerCase()) {
      return order
    }
  }

  // 模糊匹配
  for (const [key, order] of Object.entries(sectionOrder)) {
    if (sectionName.includes(key.toLowerCase())) {
      return order
    }
  }

  // 尝试提取数字进行排序
  const numberMatch = sectionName.match(/(\d+)/)
  if (numberMatch) {
    const num = parseInt(numberMatch[1])
    // 如果是1-8的数字，按照课程节次处理
    if (num >= 1 && num <= 8) {
      return num * 10
    }
  }

  // 时间格式匹配 (如: 08:30-09:15) - 从原始字符串中提取
  const timeMatch = classSection.match(/(\d{1,2}):(\d{2})/)
  if (timeMatch) {
    const hour = parseInt(timeMatch[1])
    const minute = parseInt(timeMatch[2])
    const timeOrder = hour * 60 + minute
    return timeOrder
  }

  // 默认排序
  return 999
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LabScheduleApi.getLabSchedulePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 视图模式切换 */
const handleViewModeChange = (mode: string) => {
  viewMode.value = mode
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await LabScheduleApi.deleteLabSchedule(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除机房实训室课 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await LabScheduleApi.deleteLabScheduleList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: LabSchedule[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导入按钮操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await LabScheduleApi.exportLabSchedule(queryParams)
    download.excel(data, '机房实训室课.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}





/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 表格容器样式 */
.table-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  overflow-x: auto;
}

.basic-info {
  text-align: left;
  padding: 8px 0;
}

.info-row {
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.info-row:last-child {
  margin-bottom: 0;
}

.course-cell {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  word-break: break-word;
  line-height: 1.4;
  font-size: 13px;
}

.course-cell:empty::before {
  content: '-';
  color: #999;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

:deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}

/* 标签样式 */
:deep(.el-tag) {
  margin: 1px;
  font-size: 11px;
}

/* 分页居中 */
:deep(.el-pagination) {
  justify-content: center;
  margin-top: 20px;
}

/* 课程表视图样式 */
.schedule-view {
  padding: 16px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  overflow-x: auto;
}

.class-schedule-card {
  margin-bottom: 32px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  min-width: 1200px;
  overflow-x: auto;
}

.class-header {
  padding: 16px 20px;
  background: linear-gradient(135deg, #334fca 0%, rgb(255, 255, 255) 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.class-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.class-info {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.class-info :deep(.el-tag) {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.schedule-table {
  margin: 0 auto;
  width: 100%;
}

.schedule-table :deep(.el-table__header-wrapper) {
  background: #f8f9fa;
}

.schedule-table :deep(.el-table th) {
  background: #f8f9fa !important;
  font-weight: 600;
  color: #495057;
}

.schedule-course {
  padding: 8px;
  border-radius: 4px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  min-height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  word-break: break-word;
  line-height: 1.4;
  font-size: 13px;
  margin: 4px;
}

.schedule-course:empty::before {
  content: '-';
  color: #6c757d;
}

.section-cell {
  padding: 8px;
  text-align: center;
}

.section-name {
  font-weight: 600;
  color: #495057;
  font-size: 14px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .basic-info {
    font-size: 12px;
  }

  .course-cell {
    font-size: 12px;
    min-height: 28px;
  }

  .class-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .schedule-course {
    font-size: 12px;
    min-height: 36px;
  }
}
</style>
